package com.ckmod.zyr3x.tools.components;

import android.app.Application;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Path;
import android.os.Build;
import android.text.BoringLayout;
import com.ckmod.zyr3x.tools.R;
import org.apache.http.client.protocol.ClientContext;

import java.io.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by IntelliJ IDEA.
 * User: Olex
 * Date: 14.01.11
 * Time: 22:48
 * To change this template use File | Settings | File Templates.
 */
public class CSSConfig {

        private static int countOptions = 74;
        private static ArrayList<String> options = new ArrayList<String>();
        private static ArrayList<String> values = new ArrayList<String>();
        private static String bin_ss4n1 = "/system/bin/ss4n1";
        private static String config = "/system/etc/ss4n1.conf";
        private static String tmp_bin_ss4n1 = "/sdcard/ss4n1/tmp/ss4n1";
        private static String tmp_config = "/sdcard/ss4n1/tmp/ss4n1.conf";
        private static Boolean isNew = false;
        // AWAKE mode CAVS table
        private static String AWAKE_CAVS  ="A128000=128000,950,975" +
                                    "\nA245000=245000,950,1000" +
                                    "\nA384000=384000,950,1025" +
                                    "\nA422400=422400,950,1050" +
                                    "\nA460800=460800,975,1050" +
                                    "\nA499200=499200,1000,1075"  +
                                    "\nA537600=537600,1000,1075"  +
                                    "\nA576000=576000,1025,1100"  +
                                    "\nA614400=614400,1050,1100"  +
                                    "\nA652800=652800,1075,1125"  +
                                    "\nA691200=691200,1100,1150"  +
                                    "\nA729600=729600,1125,1175"  +
                                    "\nA768000=768000,1150,1200"  +
                                    "\nA806400=806400,1175,1225"  +
                                    "\nA844800=844800,1200,1250"  +
                                    "\nA883200=883200,1200,1275"  +
                                    "\nA921600=921600,1225,1275"  +
                                    "\nA960000=960000,1225,1275"  +
                                    "\nA998400=998400,1225,1275"  +
                                    "\nA1036800=1036800,1275,1275" +
                                    "\nA1075200=1075200,1275,1275" +
                                    "\nA1113600=1113600,1275,1275";

    private static String SLEEP_CAVS  = "S128000=128000,950,975" +
                                "\nS245000=245000,950,1000" +
                                "\nS384000=384000,950,1025" +
                                "\nS422400=422400,950,1050" +
                                "\nS460800=460800,975,1050" +
                                "\nS499200=499200,1000,1075" +
                                "\nS537600=537600,1000,1075" +
                                "\nS576000=576000,1025,1100" +
                                "\nS614400=614400,1050,1100" +
                                "\nS652800=652800,1075,1125" +
                                "\nS691200=691200,1100,1150" +
                                "\nS729600=729600,1125,1175" +
                                "\nS768000=768000,1150,1200" +
                                "\nS806400=806400,1175,1225" +
                                "\nS844800=844800,1200,1250" +
                                "\nS883200=883200,1200,1275" +
                                "\nS921600=921600,1225,1275" +
                                "\nS960000=960000,1225,1275" +
                                "\nS998400=998400,1225,1275" +
                                "\nS1036800=1036800,1275,1275" +
                                "\nS1075200=1075200,1275,1275" +
                                "\nS1113600=1113600,1275,1275";

    public static void init(final SharedPreferences sharedPreferences, final Resources resources)
    {
        initSDData();

        Integer install =  sharedPreferences.getInt("INSTALL", 0);
        String version =  sharedPreferences.getString("VERSION", "");
        load(null);
        if(install == 0 || !version.equals(resources.getString(R.string.version)) || !initSS4n1() || options.size() < countOptions )
        {
            install();
            sharedPreferences.edit().putInt("INSTALL",1).commit();
            sharedPreferences.edit().putString("VERSION",resources.getString(R.string.version)).commit();
        }
        load(null);

    }

    private static boolean initSS4n1()
    {
        return (new File(bin_ss4n1)).exists();
    }

    private static void install()
    {

        CSystem.mountSystem();
        CSystem.rootCommand("mkdir -p /sdcard/ss4n1/tmp/");
        CSystem.chmod("777", config);
        CSystem.chmod("777", bin_ss4n1);
        CSystem.rootCommand(install_ss4n1);
        FileWriter ss4n1 = null;

        try {
            ss4n1 = new FileWriter(tmp_bin_ss4n1);
            ss4n1.write(system_bin_ss4n1);
            ss4n1.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        CSystem.rootCommand("cp -f "+tmp_bin_ss4n1+" "+bin_ss4n1);


        try {
            ss4n1 = new FileWriter(tmp_config);
            ss4n1.write(system_etc_ss4n1);
             ss4n1.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        CSystem.rootCommand("cp -f "+tmp_config+" "+config);

        CSystem.unmountSystem();

    }

    public static void initSDData()
    {
        boolean exists = (new File("/sdcard/ss4n1/")).exists();
        if (!exists) {
           CSystem.rootCommand("mkdir -p /sdcard/ss4n1/tmp/");
        }
    }

    public static void load(String dir) {
        CSystem.mountSystem();
        CSystem.chmod("777", config);

        if(dir == null) dir = config;
        String line;
        options = new ArrayList<String>();
        values = new ArrayList<String>();
        FileReader f = null;
        BufferedReader br = null;
        try {
            if ((new File(dir).exists())) {
                f = new FileReader(dir);
                br = new BufferedReader(f);

                try {
                    while ((line = br.readLine()) != null) {
                        if(line.split("#").length == 1){
                        String[] param = line.split("=");
                        options.add(param[0]);

                        if(param.length == 1)
                            values.add("");
                        else
                            values.add(param[1]);
                        }
                    }
                    options = GetUniqueValues(options);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            else
            {
                createConfig();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

               CSystem.unmountSystem();
    }

    public static ArrayList<String> getOptions() {
            return options;  //To change body of created methods use File | Settings | File Templates.
        }

    public static ArrayList<String> getValues() {
            return values;  //To change body of created methods use File | Settings | File Templates.
        }

    public static void setValues(ArrayList<String> val) {
            values = val;
    }

    public static void setValue(String name, String val)
    {
          values.set(options.indexOf(name),val);
          update();
    }

    public static String getValue(String name)
    {
         return values.get(options.indexOf(name));
    }

    public static void update()
    {
        save(null);
        stop();
        start();
    }

    public static void saveCurrent(String name, String dir)
    {
        CSystem.mountSystem();
        CSystem.chmod("777", config);
        CSystem.rootCommand("mkdir -p /sdcard/ss4n1/");
        CSystem.rootCommand("cp -f "+config+"  /sdcard/ss4n1/"+name+".conf");
        CSystem.unmountSystem();
    }

    private static int profilePreload(String filedir)
    {
        String line;
        ArrayList<String> opt = new ArrayList<String>();
        ArrayList<String> val= new ArrayList<String>();
        FileReader f = null;
        BufferedReader br = null;
        try {
            if ((new File(filedir).exists())) {
                f = new FileReader(filedir);
                br = new BufferedReader(f);

                try {
                    while ((line = br.readLine()) != null) {
                        if(line.split("#").length == 1){
                        String[] param = line.split("=");
                        opt.add(param[0]);

                        if(param.length == 1)
                            val.add("");
                        else
                            val.add(param[1]);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return   opt.size();
    }

    public static ArrayList GetUniqueValues(ArrayList values)
    {
        return values; //return new ArrayList(new HashSet(values));
    }

    public static int GetOptionsSize()
    {
        return (new ArrayList(new HashSet(options))).size();
    }
    public static boolean saveProfilesName(String name)
    {
        int size =profilePreload("/sdcard/ss4n1/"+name+".conf");
        if(size == GetOptionsSize())
        {
            CSystem.mountSystem();
            CSystem.chmod("777", config);
            CSystem.rootCommand("cp -f /sdcard/ss4n1/"+name+".conf "+config);
            CSystem.unmountSystem();
            load(null);
            stop();
            start();
            return true;
        }

        return false;
    }

    public static void deleteProfilesName(String name)
    {
        CSystem.rootCommand("rm /sdcard/ss4n1/"+name+".conf");
    }

    public static String[] loadProfilesList(){

        String list[] = new File("/sdcard/ss4n1/").list();
        ArrayList<String> retList = new ArrayList<String>();
        for(int i=0;i <  list.length; i++)
            if(list[i].indexOf(".conf") != -1)
                 retList.add(list[i].replace(".conf", ""));

        String[] rsList = new String[retList.size()];
        for(int i=0;i <  retList.size(); i++)
               rsList[i] = retList.get(i);
        return rsList;
    }

    public static void save(String saveDir)
    {
        CSystem.mountSystem();
        FileWriter f = null;
        if(saveDir == null) saveDir = config;

        try {
            options = GetUniqueValues(options);
            f = new FileWriter(config);
            for (int i = 0; i < options.size(); i++) {
                String opt = options.get(i).toString() + "=" + values.get(i).toString()+"\n";
                f.write(opt);
            }
            if(isNew == true)
            {
               f.write(AWAKE_CAVS);
               f.write(SLEEP_CAVS);
            }

            f.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        CSystem.unmountSystem();
    }

    public static void createConfig()
    {
        //isNew = true;

        options.add("ENABLE_SS4N1");
        options.add("ENABLE_MAXPHONE");
        options.add("DEWONKIFIER");
        options.add("TWEAK_NOATIME");
        options.add("TWEAK_STORAGE");
        options.add("TWEAK_UI");
        options.add("TWEAK_NETWORK");
        options.add("ENABLE_SWITCH");

        options.add("SWITCH_UV");
        options.add("SWITCH_CPUSCHED");
        options.add("SWITCH_VM");
        options.add("SWITCH_CPUFREQ");

        options.add("AWAKE_GOVERNOR");
        options.add("AWAKE_MIN_FREQ");
        options.add("AWAKE_MAX_FREQ");
        options.add("AWAKE_UP_THRESHOLD");
        options.add("AWAKE_MIN_UV");
        options.add("AWAKE_MAX_UV");

        options.add("SLEEP_GOVERNOR");
        options.add("SLEEP_MIN_FREQ");
        options.add("SLEEP_MAX_FREQ");
        options.add("SLEEP_UP_THRESHOLD");
        options.add("SLEEP_MIN_UV");
        options.add("SLEEP_MAX_UV");

        options.add("CHARG_GOVERNOR");
        options.add("CHARG_MIN_FREQ");
        options.add("CHARG_MAX_FREQ");
        options.add("CHARG_UP_THRESHOLD");
        options.add("CHARG_MIN_UV");
        options.add("CHARG_MAX_UV");

        values.add("0");
        values.add("1");
        values.add("1");
        values.add("1");
        values.add("1");
        values.add("1");
        values.add("1");
        values.add("1");

        values.add("1");
        values.add("1");
        values.add("1");
        values.add("1");

        values.add("interactive");
        values.add("245000");
        values.add("998400");
        values.add("");
        values.add("0");
        values.add("0");

        values.add("conservative");
        values.add("245000");
        values.add("998400");
        values.add("99");
        values.add("0");
        values.add("0");

        values.add("performance");
        values.add("998400");
        values.add("998400");
        values.add("");
        values.add("0");
        values.add("0");
    }

    public static void stop()
    {
       CSystem.kill("ss4n1");
    }

    public static void start()
    {
       CSystem.rootCommand("/system/bin/ss4n1 > /dev/nul &");
    }


    private static String install_ss4n1 ="EXIST=`cat /system/etc/init.local.rc|grep ss4n1`;\n" +
            "        if [ ! \"$EXIST\" ];\n" +
            "        then\n" +
            "            mount -o remount,rw /system;\n" +
            "            echo \"\" >> /system/etc/init.local.rc;\n" +
            "            echo \"service ss4n1 /system/bin/ss4n1\" >> /system/etc/init.local.rc;\n" +
            "            echo \"        oneshot\" >> /system/etc/init.local.rc;\n" +
            "            mount -o remount,ro /system;\n" +
            "        fi;";

    private static String system_etc_ss4n1 = "# Initialization for SS4N1\n" +
            "ENABLE_SS4N1=0\n" +
            "ENABLE_MAXPHONE=1\n" +
            "DEWONKIFIER=1\n" +
            "TWEAK_NOATIME=1\n" +
            "TWEAK_STORAGE=1\n" +
            "TWEAK_UI=1\n" +
            "TWEAK_NETWORK=1\n" +
            "ENABLE_SWITCH=1\n" +
            "SWITCH_UV=1\n" +
            "SWITCH_CPUSCHED=1\n" +
            "SWITCH_VM=1\n" +
            "SWITCH_CPUFREQ=1\n" +
            "AWAKE_GOVERNOR=interactive\n" +
            "AWAKE_MIN_FREQ=245000\n" +
            "AWAKE_MAX_FREQ=998400\n" +
            "AWAKE_UP_THRESHOLD=\n" +
            "AWAKE_MIN_UV=0\n" +
            "AWAKE_MAX_UV=0\n" +
            "SLEEP_GOVERNOR=conservative\n" +
            "SLEEP_MIN_FREQ=245000\n" +
            "SLEEP_MAX_FREQ=998400\n" +
            "SLEEP_UP_THRESHOLD=99\n" +
            "SLEEP_MIN_UV=0\n" +
            "SLEEP_MAX_UV=0\n" +
            "CHARG_GOVERNOR=performance\n" +
            "CHARG_MIN_FREQ=998400\n" +
            "CHARG_MAX_FREQ=998400\n" +
            "CHARG_UP_THRESHOLD=\n" +
            "CHARG_MIN_UV=0\n" +
            "CHARG_MAX_UV=0\n" +
            "# AWAKE mode CAVS table\n" +
            "A128000=128000,950,975\n" +
            "A245000=245000,950,1000\n" +
            "A384000=384000,950,1025\n" +
            "A422400=422400,950,1050\n" +
            "A460800=460800,975,1050\n" +
            "A499200=499200,1000,1075\n" +
            "A537600=537600,1000,1075\n" +
            "A576000=576000,1025,1100\n" +
            "A614400=614400,1050,1100\n" +
            "A652800=652800,1075,1125\n" +
            "A691200=691200,1100,1150\n" +
            "A729600=729600,1125,1175\n" +
            "A768000=768000,1150,1200\n" +
            "A806400=806400,1175,1225\n" +
            "A844800=844800,1200,1250\n" +
            "A883200=883200,1200,1275\n" +
            "A921600=921600,1225,1275\n" +
            "A960000=960000,1225,1275\n" +
            "A998400=998400,1225,1275\n" +
            "A1036800=1036800,1275,1275\n" +
            "A1075200=1075200,1275,1275\n" +
            "A1113600=1113600,1275,1275\n" +
            "S128000=128000,950,975\n" +
            "S245000=245000,950,1000\n" +
            "S384000=384000,950,1025\n" +
            "S422400=422400,950,1050\n" +
            "S460800=460800,975,1050\n" +
            "S499200=499200,1000,1075\n" +
            "S537600=537600,1000,1075\n" +
            "S576000=576000,1025,1100\n" +
            "S614400=614400,1050,1100\n" +
            "S652800=652800,1075,1125\n" +
            "S691200=691200,1100,1150\n" +
            "S729600=729600,1125,1175\n" +
            "S768000=768000,1150,1200\n" +
            "S806400=806400,1175,1225\n" +
            "S844800=844800,1200,1250\n" +
            "S883200=883200,1200,1275\n" +
            "S921600=921600,1225,1275\n" +
            "S960000=960000,1225,1275\n" +
            "S998400=998400,1225,1275\n" +
            "S1036800=1036800,1275,1275\n" +
            "S1075200=1075200,1275,1275\n" +
            "S1113600=1113600,1275,1275";

    private static String system_bin_ss4n1 = ". /system/etc/ss4n1.conf;\n" +
            "\n" +
            "        if [ $ENABLE_SS4N1 -ne 1 ];\n" +
            "        then\n" +
            "            log -p i -t SS4N1 \"*** DISABLED *** exiting...\";\n" +
            "            exit;\n" +
            "        fi;\n" +
            "        \n" +
            "        # One-time tweaks to apply on every boot\n" +
            "        #\n" +
            "        # Remount all partitions with noatime\n" +
            "        if [ $TWEAK_NOATIME -eq 1 ];\n" +
            "        then\n" +
            "            PART=`mount | cut -d \" \" -f3`;\n" +
            "            for k in $PART;\n" +
            "            do\n" +
            "                sync;\n" +
            "                mount -o remount,noatime $k;\n" +
            "            done;\n" +
            "            log -p i -t SS4N1 \"*** NOATIME *** remounted all partitions with noatime\";\n" +
            "        fi;\n" +
            "        \n" +
            "        # Optimize non-rotating storage and i/o scheduler \n" +
            "        if [ $TWEAK_STORAGE -eq 1 ];\n" +
            "        then\n" +
            "            LOOP=`ls -d /sys/block/loop*`;\n" +
            "            MMC=`ls -d /sys/block/mmc*`;\n" +
            "            MTD=`ls -d /sys/block/mtd*`;\n" +
            "        \n" +
            "            for i in $LOOP $MMC $MTD;\n" +
            "            do\n" +
            "                echo 256 > $i/queue/read_ahead_kb;\n" +
            "                echo 0 > $i/queue/rotational; \n" +
            "                if [ -e $i/queue/iosched/back_seek_penalty ];\n" +
            "                then\n" +
            "                    echo 1 > $i/queue/iosched/back_seek_penalty;\n" +
            "                    echo 0 > $i/queue/iosched/slice_idle;\n" +
            "                elif [ -e $i/queue/iosched/fifo_batch ];\n" +
            "                then\n" +
            "                    echo 1 > $i/queue/iosched/fifo_batch;\n" +
            "                fi;\n" +
            "            done;\n" +
            "            echo 3072 > /sys/devices/virtual/bdi/179:0/read_ahead_kb;\n" +
            "            log -p i -t SS4N1 \"*** STORAGE *** applied storage and I/O tweaks\";\n" +
            "        fi;\n" +
            "        \n" +
            "        if [ $TWEAK_UI -eq 1 ];\n" +
            "        then\n" +
            "            setprop windowsmgr.max_events_per_sec 60;\n" +
            "            log -p i -t SS4N1 \"*** UI *** applied UI/homescreen tweak\";\n" +
            "        fi;\n" +
            "        \n" +
            "        if [ $DEWONKIFIER -eq 1 ];\n" +
            "        then\n" +
            "            setprop media.a1026.enableA1026 0;\n" +
            "            log -p i -t SS4N1 \"*** DEWONKIFIER *** disabled A1026 noise-cancelling mic\";\n" +
            "        else\n" +
            "            setprop media.a1026.enableA1026 1;\n" +
            "        fi;\n" +
            "        \n" +
            "        if [ $TWEAK_NETWORK -eq 1 ];\n" +
            "        then\n" +
            "            setprop wifi.supplicant_scan_interval 180;\n" +
            "            setprop net.tcp.buffersize.default 4096,87380,174760,4096,16384,131072;\n" +
            "            setprop net.tcp.buffersize.wifi 4095,87380,174760,4096,16384,131072;\n" +
            "            setprop net.tcp.buffersize.umts 4094,87380,174760,4096,16384,131072;\n" +
            "            echo 262144 > /proc/sys/net/core/netdev_max_backlog;\n" +
            "            echo 262144 > /proc/sys/net/core/somaxconn;\n" +
            "            echo 65535 > /proc/sys/net/core/rmem_default;\n" +
            "            echo 174760 > /proc/sys/net/core/rmem_max;\n" +
            "            echo 65535 > /proc/sys/net/core/wmem_default;\n" +
            "            echo 131072 > /proc/sys/net/core/wmem_max;\n" +
            "            echo 4096 16384 131072 > /proc/sys/net/ipv4/tcp_wmem;\n" +
            "            echo 4096 87380 174760 > /proc/sys/net/ipv4/tcp_rmem;\n" +
            "            echo 15 > /proc/sys/net/ipv4/tcp_fin_timeout;\n" +
            "            echo 1200 > /proc/sys/net/ipv4/tcp_keepalive_time;\n" +
            "            echo 360000 > /proc/sys/net/ipv4/tcp_max_tw_buckets;\n" +
            "            echo 5 > /proc/sys/net/ipv4/tcp_reordering;\n" +
            "            echo 0 > /proc/sys/net/ipv4/tcp_slow_start_after_idle;\n" +
            "            echo 3 > /proc/sys/net/ipv4/tcp_syn_retries;\n" +
            "            echo 2 > /proc/sys/net/ipv4/tcp_synack_retries;\n" +
            "            echo 0 > /proc/sys/net/ipv4/tcp_timestamps;\n" +
            "            echo 1 > /proc/sys/net/ipv4/tcp_tw_recycle;\n" +
            "            echo 1 > /proc/sys/net/ipv4/tcp_tw_reuse;\n" +
            "            echo 0 > /proc/sys/net/ipv4/tcp_window_scaling;\n" +
            "            log -p i -t SS4N1 \"*** NETWORK *** applied WIFI and TCP tweaks\";\n" +
            "        fi;\n" +
            "        \n" +
            "        AWAKE_MODE() # Screen-ON\n" +
            "        {\n" +
            "        # AVS Undervolting\n" +
            "        if [ $SWITCH_UV -eq 1 ]; \n" +
            "        then\n" +
            "            if [ -e /sys/module/avs/parameters/avs_adjust ];\n" +
            "            then\n" +
            "                for i in $ALLFREQS;\n" +
            "                do\n" +
            "                    eval echo \\$A$i > /sys/module/avs/parameters/avs_adjust;\n" +
            "                    usleep 50000;\n" +
            "                done;\n" +
            "                log -p i -t SS4N1 \"*** AWAKE *** Screen-ON settings for undervolting CAVS kernel\";\n" +
            "            fi;\n" +
            "            if [ -e /sys/devices/system/cpu/cpu0/cpufreq/vdd_levels_havs ]\n" +
            "            then\n" +
            "                TEMPMIN=`head -n1 /sys/devices/system/cpu/cpu0/cpufreq/vdd_levels_havs | awk '{print $2}'`;\n" +
            "                TEMPMAX=`head -n1 /sys/devices/system/cpu/cpu0/cpufreq/vdd_levels_havs | awk '{print $3}'`\n" +
            "                RESETMIN=`expr 950 \"-\" $TEMPMIN`;\n" +
            "                RESETMAX=`expr 975 \"-\" $TEMPMAX`;\n" +
            "                echo $RESETMIN $RESETMAX > /sys/devices/system/cpu/cpu0/cpufreq/vdd_levels_havs;\n" +
            "                echo \"-$AWAKE_MIN_UV\" \"-$AWAKE_MAX_UV\" > /sys/devices/system/cpu/cpu0/cpufreq/vdd_levels_havs;\n" +
            "                log -p i -t SS4N1 \"*** AWAKE *** Screen-ON settings for undervolting HAVS kernel: min=$AWAKE_MIN_UV, max=$AWAKE_MAX_UV\";\n" +
            "            fi;\n" +
            "        fi;\n" +
            "        \n" +
            "        # CPUfreq governor\n" +
            "        if [ $SWITCH_CPUFREQ -eq 1 ]\n" +
            "        then\n" +
            "            echo $AWAKE_GOVERNOR > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor;\n" +
            "            echo $AWAKE_MAX_FREQ > /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq;\n" +
            "            echo $AWAKE_MIN_FREQ > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq;\n" +
            "            if [ -e /sys/devices/system/cpu/cpufreq/$AWAKE_GOVERNOR/up_threshold ];\n" +
            "            then\n" +
            "                echo $AWAKE_UP_THRESHOLD > /sys/devices/system/cpu/cpufreq/$AWAKE_GOVERNOR/up_threshold;\n" +
            "            fi;\n" +
            "            log -p i -t SS4N1 \"*** AWAKE *** Screen-ON settings for CPUfreq governor, Gov=$AWAKE_GOVERNOR, Min=$AWAKE_MIN_FREQ, Max=$AWAKE_MAX_FREQ\";\n" +
            "        fi;\n" +
            "        \n" +
            "        # CPU scheduler\n" +
            "        if [ $SWITCH_CPUSCHED -eq 1 ]\n" +
            "        then\n" +
            "            if [ -e /proc/sys/kernel/rr_interval ];\n" +
            "            then\n" +
            "                # BFS\n" +
            "                echo 1 > /proc/sys/kernel/rr_interval;\n" +
            "                echo 100 > /proc/sys/kernel/iso_cpu;\n" +
            "            else\n" +
            "                # CFS\n" +
            "                if [ -e /proc/sys/kernel/sched_latency_ns ];\n" +
            "                then\n" +
            "                    echo 1000000 > /proc/sys/kernel/sched_latency_ns;\n" +
            "                fi;\n" +
            "                if [ -e /proc/sys/kernel/sched_wakeup_granularity_ns ];\n" +
            "                then\n" +
            "                    echo 25000 > /proc/sys/kernel/sched_wakeup_granularity_ns;\n" +
            "                fi;\n" +
            "                if [ -e /proc/sys/kernel/sched_min_granularity_ns ];\n" +
            "                then\n" +
            "                    echo 100000 > /proc/sys/kernel/sched_min_granularity_ns;\n" +
            "                fi;\n" +
            "                echo -1 > /proc/sys/kernel/sched_rt_runtime_us; \n" +
            "                echo 100000 > /proc/sys/kernel/sched_rt_period_us;\n" +
            "                echo 95000 > /proc/sys/kernel/sched_rt_runtime_us;\n" +
            "            fi;\n" +
            "            log -p i -t SS4N1 \"*** AWAKE *** Screen-ON settings for CPU scheduler\";\n" +
            "        fi;\n" +
            "        \n" +
            "        # VM parameters\n" +
            "        if [ $SWITCH_VM -eq 1 ]\n" +
            "        then\n" +
            "            echo 30 > /proc/sys/vm/swappiness;\n" +
            "            echo 3000 > /proc/sys/vm/dirty_expire_centisecs;\n" +
            "            echo 500 > /proc/sys/vm/dirty_writeback_centisecs;\n" +
            "            echo 10 > /proc/sys/vm/dirty_background_ratio;\n" +
            "            echo 40 > /proc/sys/vm/dirty_ratio;\n" +
            "            echo 0 > /proc/sys/vm/page-cluster;\n" +
            "            echo 0 > /proc/sys/vm/laptop_mode;\n" +
            "            echo 300 > /proc/sys/vm/vfs_cache_pressure;\n" +
            "            echo 5120 > /proc/sys/vm/min_free_kbytes;\n" +
            "            log -p i -t SS4N1 \"*** AWAKE *** Screen-ON settings for Virtual Memory\";\n" +
            "        fi;\n" +
            "        }\n" +
            "        \n" +
            "        CHARG_MODE() # CHARGING-ON\n" +
            "        {\n" +
            "        # AVS Undervolting\n" +
            "        if [ $SWITCH_UV -eq 1 ]; \n" +
            "        then\n" +
            "            if [ -e /sys/module/avs/parameters/avs_adjust ];\n" +
            "            then\n" +
            "                for i in $ALLFREQS;\n" +
            "                do\n" +
            "                    eval echo \\$A$i > /sys/module/avs/parameters/avs_adjust;\n" +
            "                    usleep 50000;\n" +
            "                done;\n" +
            "                log -p i -t SS4N1 \"*** CHARGING *** Screen-ON settings for undervolting CAVS kernel\";\n" +
            "            fi;\n" +
            "            if [ -e /sys/devices/system/cpu/cpu0/cpufreq/vdd_levels_havs ]\n" +
            "            then\n" +
            "                TEMPMIN=`head -n1 /sys/devices/system/cpu/cpu0/cpufreq/vdd_levels_havs | awk '{print $2}'`;\n" +
            "                TEMPMAX=`head -n1 /sys/devices/system/cpu/cpu0/cpufreq/vdd_levels_havs | awk '{print $3}'`\n" +
            "                RESETMIN=`expr 950 \"-\" $TEMPMIN`;\n" +
            "                RESETMAX=`expr 975 \"-\" $TEMPMAX`;\n" +
            "                echo $RESETMIN $RESETMAX > /sys/devices/system/cpu/cpu0/cpufreq/vdd_levels_havs;\n" +
            "                echo \"-$CHARG_MIN_UV\" \"-$CHARG_MAX_UV\" > /sys/devices/system/cpu/cpu0/cpufreq/vdd_levels_havs;\n" +
            "                log -p i -t SS4N1 \"*** CHARGING *** CHARGING-ON settings for undervolting HAVS kernel: min=$CHARG_MIN_UV, max=$CHARG_MAX_UV\";\n" +
            "            fi;\n" +
            "        fi;\n" +
            "        \n" +
            "        # CPUfreq governor\n" +
            "        if [ $SWITCH_CPUFREQ -eq 1 ]\n" +
            "        then\n" +
            "            echo $CHARG_GOVERNOR > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor;\n" +
            "            echo $CHARG_MAX_FREQ > /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq;\n" +
            "            echo $CHARG_MIN_FREQ > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq;\n" +
            "            if [ -e /sys/devices/system/cpu/cpufreq/$CHARG_GOVERNOR/up_threshold ];\n" +
            "            then\n" +
            "                echo $CHARG_UP_THRESHOLD > /sys/devices/system/cpu/cpufreq/$CHARG_GOVERNOR/up_threshold;\n" +
            "            fi;\n" +
            "            log -p i -t SS4N1 \"*** CHARGING *** CHARGING-ON settings for CPUfreq governor, Gov=$CHARG_GOVERNOR, Min=$CHARG_MIN_FREQ, Max=$CHARG_MAX_FREQ\";\n" +
            "        fi;\n" +
            "        \n" +
            "        # CPU scheduler\n" +
            "        if [ $SWITCH_CPUSCHED -eq 1 ]\n" +
            "        then\n" +
            "            if [ -e /proc/sys/kernel/rr_interval ];\n" +
            "            then\n" +
            "                # BFS\n" +
            "                echo 1 > /proc/sys/kernel/rr_interval;\n" +
            "                echo 100 > /proc/sys/kernel/iso_cpu;\n" +
            "            else\n" +
            "                # CFS\n" +
            "                if [ -e /proc/sys/kernel/sched_latency_ns ];\n" +
            "                then\n" +
            "                    echo 1000000 > /proc/sys/kernel/sched_latency_ns;\n" +
            "                fi;\n" +
            "                if [ -e /proc/sys/kernel/sched_wakeup_granularity_ns ];\n" +
            "                then\n" +
            "                    echo 25000 > /proc/sys/kernel/sched_wakeup_granularity_ns;\n" +
            "                fi;\n" +
            "                if [ -e /proc/sys/kernel/sched_min_granularity_ns ];\n" +
            "                then\n" +
            "                    echo 100000 > /proc/sys/kernel/sched_min_granularity_ns;\n" +
            "                fi;\n" +
            "                echo -1 > /proc/sys/kernel/sched_rt_runtime_us; \n" +
            "                echo 100000 > /proc/sys/kernel/sched_rt_period_us;\n" +
            "                echo 95000 > /proc/sys/kernel/sched_rt_runtime_us;\n" +
            "            fi;\n" +
            "            log -p i -t SS4N1 \"*** CHARGING *** CHARGING-ON settings for CPU scheduler\";\n" +
            "        fi;\n" +
            "        \n" +
            "        # VM parameters\n" +
            "        if [ $SWITCH_VM -eq 1 ]\n" +
            "        then\n" +
            "            echo 30 > /proc/sys/vm/swappiness;\n" +
            "            echo 3000 > /proc/sys/vm/dirty_expire_centisecs;\n" +
            "            echo 500 > /proc/sys/vm/dirty_writeback_centisecs;\n" +
            "            echo 10 > /proc/sys/vm/dirty_background_ratio;\n" +
            "            echo 40 > /proc/sys/vm/dirty_ratio;\n" +
            "            echo 0 > /proc/sys/vm/page-cluster;\n" +
            "            echo 0 > /proc/sys/vm/laptop_mode;\n" +
            "            echo 300 > /proc/sys/vm/vfs_cache_pressure;\n" +
            "            echo 5120 > /proc/sys/vm/min_free_kbytes;\n" +
            "            log -p i -t SS4N1 \"*** CHARGING *** CHARGING-ON settings for Virtual Memory\";\n" +
            "        fi;\n" +
            "        }\n" +
            "        \n" +
            "        \n" +
            "        SLEEP_MODE()# Screen-OFF\n" +
            "        {\n" +
            "        # CPUfreq governor\n" +
            "        if [ $SWITCH_CPUFREQ -eq 1 ]\n" +
            "        then\n" +
            "            echo $SLEEP_GOVERNOR > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor;\n" +
            "            echo $SLEEP_MIN_FREQ > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq;\n" +
            "            echo $SLEEP_MAX_FREQ > /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq;\n" +
            "            if [ -e /sys/devices/system/cpu/cpufreq/$SLEEP_GOVERNOR/up_threshold ];\n" +
            "            then\n" +
            "                echo $SLEEP_UP_THRESHOLD > /sys/devices/system/cpu/cpufreq/$SLEEP_GOVERNOR/up_threshold;\n" +
            "            fi;\n" +
            "            log -p i -t SS4N1 \"*** SLEEP *** Screen-OFF settings for CPUfreq governor, Gov=$SLEEP_GOVERNOR, Min=$SLEEP_MIN_FREQ, Max=$SLEEP_MAX_FREQ\";\n" +
            "        fi;\n" +
            "        \n" +
            "        # CPU scheduler\n" +
            "        if [ $SWITCH_CPUSCHED -eq 1 ]\n" +
            "        then\n" +
            "            if [ -e /proc/sys/kernel/rr_interval ];\n" +
            "            then\n" +
            "                # BFS\n" +
            "                echo 7 > /proc/sys/kernel/rr_interval;\n" +
            "                echo 60 > /proc/sys/kernel/iso_cpu;\n" +
            "            else\n" +
            "                # CFS\n" +
            "                if [ -e /proc/sys/kernel/sched_latency_ns ];\n" +
            "                then\n" +
            "                    echo 10000000 > /proc/sys/kernel/sched_latency_ns;\n" +
            "                fi;\n" +
            "                if [ -e /proc/sys/kernel/sched_wakeup_granularity_ns ];\n" +
            "                then\n" +
            "                    echo 2000000 > /proc/sys/kernel/sched_wakeup_granularity_ns;\n" +
            "                fi;\n" +
            "                if [ -e /proc/sys/kernel/sched_min_granularity_ns ];\n" +
            "                then\n" +
            "                    echo 750000 > /proc/sys/kernel/sched_min_granularity_ns;\n" +
            "                fi;\n" +
            "                echo -1 > /proc/sys/kernel/sched_rt_runtime_us;\n" +
            "                echo 1000000 > /proc/sys/kernel/sched_rt_period_us;\n" +
            "                echo 950000 > /proc/sys/kernel/sched_rt_runtime_us;\n" +
            "            fi;\n" +
            "            log -p i -t SS4N1 \"*** SLEEP *** Screen-OFF settings for CPU scheduler\";\n" +
            "        fi;\n" +
            "        \n" +
            "        # VM parameters\n" +
            "        if [ $SWITCH_VM -eq 1 ]\n" +
            "        then\n" +
            "            echo 0 > /proc/sys/vm/swappiness;\n" +
            "            echo 0 > /proc/sys/vm/dirty_expire_centisecs;\n" +
            "            echo 0 > /proc/sys/vm/dirty_writeback_centisecs;\n" +
            "            echo 60 > /proc/sys/vm/dirty_background_ratio;\n" +
            "            echo 95 > /proc/sys/vm/dirty_ratio;\n" +
            "            echo 3 > /proc/sys/vm/page-cluster;\n" +
            "            echo 5 > /proc/sys/vm/laptop_mode;\n" +
            "            echo 10 > /proc/sys/vm/vfs_cache_pressure;\n" +
            "            echo 2048 > /proc/sys/vm/min_free_kbytes;\n" +
            "            log -p i -t SS4N1 \"*** SLEEP *** Screen-OFF settings for Virtual Memory\";\n" +
            "        fi;\n" +
            "        \n" +
            "        # AVS Undervolting\n" +
            "        if [ $SWITCH_UV -eq 1 ]; \n" +
            "        then\n" +
            "            if [ -e /sys/module/avs/parameters/avs_adjust ];\n" +
            "            then\n" +
            "                for i in $ALLFREQS;\n" +
            "                do\n" +
            "                    eval echo \\$S$i > /sys/module/avs/parameters/avs_adjust;\n" +
            "                    usleep 50000;\n" +
            "                done;\n" +
            "                log -p i -t SS4N1 \"*** SLEEP *** Screen-OFF settings for undervolting CAVS kernel\";\n" +
            "            fi;\n" +
            "            if [ -e /sys/devices/system/cpu/cpu0/cpufreq/vdd_levels_havs ];\n" +
            "            then\n" +
            "                TEMPMIN=`head -n1 /sys/devices/system/cpu/cpu0/cpufreq/vdd_levels_havs | awk '{print $2}'`;\n" +
            "                TEMPMAX=`head -n1 /sys/devices/system/cpu/cpu0/cpufreq/vdd_levels_havs | awk '{print $3}'`;\n" +
            "                RESETMIN=`expr 950 \"-\" $TEMPMIN`;\n" +
            "                RESETMAX=`expr 975 \"-\" $TEMPMAX`;\n" +
            "                echo $RESETMIN $RESETMAX > /sys/devices/system/cpu/cpu0/cpufreq/vdd_levels_havs;\n" +
            "                echo \"-$SLEEP_MIN_UV\" \"-$SLEEP_MAX_UV\" > /sys/devices/system/cpu/cpu0/cpufreq/vdd_levels_havs;\n" +
            "                log -p i -t SS4N1 \"*** SLEEP *** Screen-OFF settings for undervolting HAVS kernel: min=$SLEEP_MIN_UV, max=$SLEEP_MAX_UV\";\n" +
            "            fi;\n" +
            "        fi;\n" +
            "        }\n" +
            "        \n" +
            "        PROC_ADJUST()\n" +
            "        {\n" +
            "        pid=`pidof $1`;\n" +
            "        if [ $pid ];\n" +
            "        then\n" +
            "            if [ -e /proc/$pid/oom_score_adj ]; \n" +
            "            then\n" +
            "                echo -1000 > /proc/$pid/oom_score_adj; # For 2.6.37+ \n" +
            "            else\n" +
            "                echo -17 > /proc/$pid/oom_adj; # For 2.6.35\n" +
            "            fi;\n" +
            "            log -p i -t SS4N1 \"*** OOM_ADJ *** exclude process $1 from OOM killer\";\n" +
            "            if [ $2 ]\n" +
            "            then\n" +
            "                renice $2 $pid;\n" +
            "                log -p i -t SS4N1 \"*** RENICE *** set renice level $2 for process $1\";\n" +
            "            fi;\n" +
            "            exit;\n" +
            "        else\n" +
            "            sleep 1;\n" +
            "            PROC_ADJUST $1 $2;\n" +
            "        fi;\n" +
            "        }\n" +
            "        \n" +
            "        # Background process to check screen state\n" +
            "        if [ $ENABLE_SWITCH -eq 1 ];\n" +
            "        then\n" +
            "            ALLFREQS=`cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies`;\n" +
            "            (while [ 1 ]; \n" +
            "            do\n" +
            " \t\t\n" +
            "\t\tcat /sys/power/wait_for_fb_wake;\n" +
            "                POWER_STATUS=`cat /sys/class/power_supply/battery/status`;\n" +
            "                if [ $POWER_STATUS = 'Charging' ];\n" +
            "                then\t\n" +
            "                    CHARG_MODE;\n" +
            "                else\n" +
            "                    AWAKE_MODE;          \n" +
            "                fi;\n" +
            "\n" +
            "\t        cat /sys/power/wait_for_fb_sleep;\n" +
            "                POWER_STATUS=`cat /sys/class/power_supply/battery/status`;\n" +
            "                if [ $POWER_STATUS = 'Charging' ];\n" +
            "                then\t\n" +
            "                   CHARG_MODE;\n" +
            "                else\n" +
            "                   SLEEP_MODE;\n" +
            "                fi;\n" +
            "\n" +
            "            done &)\n" +
            "        fi;\n" +
            "        \n" +
            "        # One-time background process to optimize com.android.phone\n" +
            "        if [ $ENABLE_MAXPHONE -eq 1 ];\n" +
            "        then \n" +
            "            PROC_ADJUST \"com.android.phone\" \"-20\" &\n" +
            "        fi;";

}